/*
   Copyright (c) 2019 Shanghai Xuanzi Technology Co. Ltd https://xuanzi.ltd
   XZMind is licensed under the Mulan PSL v1.
   You can use this software according to the terms and conditions of the Mulan PSL v1.
   You may obtain a copy of Mulan PSL v1 at:
      http://license.coscl.org.cn/MulanPSL
   THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
   PURPOSE.
   See the Mulan PSL v1 for more details.

*/


package xuanzi.xzmind.client;
 
import java.util.HashMap;
import java.util.Map;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.dom.client.CanvasElement;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.Window.ClosingEvent;
import com.google.gwt.user.client.Window.ClosingHandler;
import com.google.gwt.user.client.ui.RootPanel;

import sbaike.client.h5.client.Action;
import sbaike.client.h5.client.ElUtils;
import sbaike.client.h5.client.JQuery;
import sbaike.client.h5.client.LocalStorage;
import xuanzi.commons.graphics.Color;
import xuanzi.commons.graphics.Paint;
import xuanzi.commons.graphics.SVGCanvas;
import xuanzi.h5.fs.client.PopupMenu;
import xuanzi.h5.fs.core.FileInfo;
import xuanzi.h5.fs.core.FileReader;
import xuanzi.h5.fs.core.FileWriter;
import xuanzi.h5.fs.core.IFile;
import xuanzi.h5.fs.core.Log;
import xuanzi.h5.fs.impl.BFileBytes;
import xuanzi.h5.fs.impl.FileSystem;
import xuanzi.h5.xzviews.client.FrameView;
import xuanzi.h5.xzviews.client.Toast;
import xuanzi.h5.xzviews.client.ViewGroup;
import xuanzi.openmind.layout.Box;
import xuanzi.openmind.lines.Line;
import xuanzi.openmind.lines.RoundLine;
import xuanzi.openmind.nodes.Node;
import xuanzi.openmind.nodes.Sheet;
import xuanzi.openmind.renders.RenderBuffer;
import xuanzi.openmind.scenes.DefaultScene;
import xuanzi.openmind.scenes.base.EastScene;
import xuanzi.openmind.scenes.base.NorthScene;
import xuanzi.openmind.scenes.base.Scene;
import xuanzi.openmind.scenes.base.SouthScene;
import xuanzi.openmind.scenes.base.ThinkTreeNorthScene;
import xuanzi.openmind.scenes.base.WestScene;
import xuanzi.openmind.shapes.Round;
import xuanzi.openmind.themes.Theme;
import xuanzi.xzmind.core.IXZMindeEditor;
import xuanzi.xzmind.core.StoreSource;
import xuanzi.xzmind.core.StoreSource.Result;
 
/**
 * 文档编辑器
 * 
 * @author 彭立铭
 *
 */
public class XZMindEditor extends FrameView implements IXZMindeEditor{
	
	String id = "xx";
	 
	
	ElUtils parent ;
	
	String path;
	
	StoreSource storeSource;
	
	public void setStoreSource(StoreSource storeSource) {
		this.storeSource = storeSource;
	}
	
	public StoreSource getStoreSource() {
		return storeSource;
	}

	private IFile currentFile;
	
	@Override
	public IFile getCurrentFile() {
		return currentFile;
	}
	
 
	
	@Override
	public String getPath() {
		return path;
	}
	 
	PrintService printService = new PrintService(this);
	
	/**
	 * 文件模块就绪，渲染文档
	 * 
	 * @param bytes	文档正文
	 */
	private void onReadyFile(String bytes) {
		ElUtils renderEl = parent.createDiv().attr("id",id);
		String theme = LocalStorage.get("fs-theme");
		boolean drak = "fs-theme-night".equals(theme);
		editorView.setTitle(storeSource.getName(currentFile)); 
		editorView.render(renderEl.toElement(), id, Window.getClientHeight()-2,drak, false,bytes);
	}
	
	private Action saveAction = new Action() {
		
		@Override
		public void execute(Element el, Event event) {
				onSave();
		}
	};
	
	@Override
	public void onLoad(ViewGroup parent) {
		add(editorView);
		super.onLoad(parent);
		Window.setTitle(storeSource.getName(currentFile)+"-玄子思维导图");
		storeSource.read(currentFile, new Result() {
			
			@Override
			public void result(String result) { 
				onReadyFile(result);
				if(storeSource.isAutoSave())
					startSaveTask();
			}
		});
	}
	
	public EditorView getEditorView() {
		return editorView;
	}
	

	EditorView editorView = new EditorView();
	
	
	KeyBindingService keyBinding = new KeyBindingService(this);

	ExportDocumentService exportService = new ExportDocumentService(this);
	
	MindCreaterService createrService = new MindCreaterService(this);
	
	ElUtils toolbarEl;

	private Action questionAction = new Action() {
		
		@Override
		public void execute(Element el, Event event) { 
			Window.open("help.html", "_blank", null);
		}
	};
	
	public ElUtils getToolbarEl() {
		return toolbarEl;
	}

	public XZMindEditor(IFile file,String filePath) {
		 
		this.path = filePath;
		currentFile = file;
		 
		parent = getEl(); 
		toolbarEl = parent.createDiv().addClass("fs-toolbar");
		toolbarEl.createEl("img").attr("src", "logo.png").addClass("fs-logo");
		toolbarEl.createSpan("玄子思维导图").addClass("fa  fs-apps");
		toolbarEl.createSpan(path.replace("/", " / ")).addClass("fa fa-folder fs-apps");
	
		createrService.onReady();
		toolbarEl.createButton(" 保  存").attr("title", "Ctrl + S 保存文件").click(saveAction).addClass("fs-fr fa fa-save");
		toolbarEl.createButton("").attr("title", "下载文件").click(exportService.downloadAction ).addClass("fs-fr fa fa-download");
		toolbarEl.createButton("").attr("title", "打印文档").click(printService.printAction ).addClass("fs-fr fa fa-print");
		toolbarEl.createButton("").attr("title", "帮助文档").click(questionAction  ).addClass("fs-fr fa fa-question");
		 
		//调整编辑器大小
		Window.addResizeHandler(new ResizeHandler() {
			
			@Override
			public void onResize(ResizeEvent event) {
				editorView.height(event.getHeight()-65);
			}
		});
		Window.addWindowClosingHandler(new ClosingHandler() {
			
			@Override
			public void onWindowClosing(ClosingEvent event) {
				onSave(); 
			}
		});
		
		Window.addCloseHandler(new CloseHandler<Window>() {
			
			@Override
			public void onClose(CloseEvent<Window> event) { 
				onSave();
				
			}
		});
 
	}
 
	/**
	 * 开始自动保存任务
	 */
	protected void startSaveTask() {
		Timer timer = new Timer() {
			
			@Override
			public void run() {
				
				storeSource.save(currentFile, editorView.getMdText(), new Result() {
					
					@Override
					public void result(String result) {
						Log.log("save ..");
					}
				}); 
			}
		};
		timer.scheduleRepeating(8*1000);
	}

	
	void onSave(){
		
		storeSource.save(currentFile, editorView.getMdText(), new Result() {
			
			@Override
			public void result(String result) {
				Log.log("save ..");
			}
		}); 
		Toast.text("保存完成").show();
	}

	

}
